package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constatns.WemediaConstants;
import com.heima.common.constatns.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.NewsAuthDto;
import com.heima.model.admin.vos.WmNewsVo;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.controller.v1.WmNewsController;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.directory.shared.kerberos.codec.apRep.actions.ApRepInit;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;


    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return PageResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 分页参数检查
        dto.checkParam();
        // 获取当前登录人的信息
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 2.分页条件查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        //条件构造器
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 状态精确查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        // 频道精确查询
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        // 时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        // 关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        // 查询当前登录用户的文章
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());
        // 发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getPublishTime);

        //查询
        wmNewsMapper.selectPage(page, lambdaQueryWrapper);
        // 3.结果返回

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    //人工审核
    @Autowired
    private WmNewsAutoScanServiceImpl wmNewsAutoScanService;

    //延迟任务
    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 发布修改文章或保存为草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {

        //0. 条件参数判断
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1. 保存或修改文章
        //对象拷贝
        WmNews wmNews = new WmNews();
        //属性拷贝 属性名称和内容相同的才能拷贝(封面图片不能拷贝
        BeanUtils.copyProperties(dto, wmNews);
        //图片拷贝
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        //图片类型转换(如果当前图片封面类型为自动-1)
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //文本内容处理  去掉最有一行 {"type":"text","value":"请在这里输入正文"}
        /*List<Map> maps = JSON.parseArray(dto.getContent(), Map.class);
        maps = maps.stream().limit(maps.size() - 1).collect(Collectors.toList());
        String context = JSON.toJSONString(maps);
        wmNews.setContent(context);*/

        saveOrUpdateWmNews(wmNews);

        //2. 判断是否为草稿 如果为草稿结束当前方法 (因为不用保存素材图片
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            //保存为草稿 不用插入素材与图片的关系
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //3.不是草稿 保存文章的图片内容与素材的关系
        //根据文章内容获取所有的图片信息
        List<String> images = ectractUrlInfo(dto.getContent());
        saveRelativeInfoForContext(images, wmNews.getId());

        //4.不是草稿 保存文章封面图片与素材的关系 如果当前布局是自动 需要匹配封面图片
        saveRelativeInfoForCover(dto, wmNews, images);

        //异步审核自媒体文章
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());  //即使出错也不会影响结果
        //添加到延迟队列
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查看文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOne(Integer id) {

        //1.检查参数
        if (id == null || id == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询数据
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {

        //1.检查参数
        if (id == null || id == 0) {
            return ResponseResult.errorResult(501, "文章Id不可缺少");
        }
        //2.查询数据
        WmNews wmNews = wmNewsMapper.selectById(id);

        //获取app端文章id 用于kafka
        Long articleId = wmNews.getArticleId();

        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3. 文章是否发布

        if (wmNews.getStatus().equals(9)) {
            return ResponseResult.errorResult(501, "文章已发布,不能删除");
        }
        //4.删除文章
        wmNewsMapper.deleteById(id);
        //5. 删除文章与图片关联表
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));

        //TODO kafka通知app端删除文章
        if (articleId != null) {
            log.info("生产者发送删除通知----------");
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_DELETE_TOPIC, JSON.toJSONString(articleId));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章上下架
     *
     * @return
     */
    @Override
    public ResponseResult downOrUpNews(WmNewsDto dto) {
        //1.检验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章id不可缺少");
        }
        //2.查询文章信息
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章不是已发布状态,不能上下架");
        }
        //3.更新自媒体端文章表
        wmNews.setEnable(dto.getEnable());
        wmNewsMapper.updateById(wmNews);

        //TODO 4. kafka消息通知 通知app端上下架文章
        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", wmNews.getEnable());
            //发送消息
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        }

        //5.返回数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

//TODO ----------------------------------------------------------------------------------admin端相关接口


    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 管理端分页分页查询列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listByPage(NewsAuthDto dto) {

        //检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //分页参数检查
        dto.checkParam();
        //分页查询自媒体文章
        IPage page = new Page(dto.getPage(), dto.getSize());

        //条件构造器
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //可以按照标题模糊查询
        lambdaQueryWrapper.like(dto.getTitle() != null, WmNews::getTitle, dto.getTitle());
        //可以按照审核状态进行精确检索
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //文章查询按照创建时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        wmNewsMapper.selectPage(page, lambdaQueryWrapper);

        //注意：需要展示作者名称
        List<WmNews> records = page.getRecords();
        List<WmNewsVo> wmNewsVos = records.stream().map(new Function<WmNews, WmNewsVo>() {
            @Override
            public WmNewsVo apply(WmNews wmNews) {
                //TODO 将作者名称拷贝到WmNewsVo中
                WmNewsVo wmNewsVo = new WmNewsVo();
                BeanUtils.copyProperties(wmNews, wmNewsVo);

                //根据用户id关联查询作者名
                Integer userId = wmNews.getUserId();
                WmUser wmUser = wmUserMapper.selectById(userId);
                wmNewsVo.setAuthorName(wmUser.getName());
                return wmNewsVo;
            }
        }).collect(Collectors.toList());

        //返回结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(wmNewsVos);
        return responseResult;
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getOneInAdmin(Integer id) {
        //检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmNewsVo wmNewsVo = new WmNewsVo();

        //查询文章信息
        WmNews wmNews = wmNewsMapper.selectById(id);

        //TODO 将作者名称拷贝到WmNewsVo中
        BeanUtils.copyProperties(wmNews, wmNewsVo);

        //根据用户id关联查询作者名
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wmUserMapper.selectById(userId);
        wmNewsVo.setAuthorName(wmUser.getName());

        //返回结果

        return ResponseResult.okResult(wmNewsVo);
    }

    /**
     * 文章人工审核失败
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult fail(NewsAuthDto dto) {

        //检查参数
        if (dto == null && dto.getId() != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询数据
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //更新数据
        wmNews.setStatus((short) dto.getStatus().intValue()); //Integer转为Short类型
        wmNews.setReason(dto.getTitle());
        wmNewsMapper.updateById(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章人工审核成功
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult pass(NewsAuthDto dto) {
        //检查参数
        if (dto == null && dto.getId() != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询数据
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //更新数据
        wmNews.setStatus((short) dto.getStatus().intValue()); //Integer转为Short类型
        wmNews.setReason("人工审核通过");
        wmNewsMapper.updateById(wmNews);
        log.info("人工审核通过异步保存app端文章信息");

        //如果不存在违规，则需要创建app端的文章信息，并更新自媒体文章的状态
        //1.异步审核自媒体文章
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());  //即使出错也不会影响结果
        //2.同步审核
        wmNewsAutoScanService.AuthPass(wmNews);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 保存或修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {

        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);  //默认上架

        if (wmNews.getId() == null) {
            //第一次创建的时间
            wmNews.setCreatedTime(new Date());
            //保存的操作
            wmNewsMapper.insert(wmNews);
        } else {
            //修改的操作

            //Short status = wmNewsMapper.selectById(wmNews.getId()).getStatus(); //获取状态 （如 未通过审核状态

            //删除图片与素材的关系
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
            //修改
            wmNewsMapper.updateById(wmNews);
        }

    }

    /**
     * 提取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {

        List<String> materials = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String value = map.get("value").toString();
                materials.add(value);
            }
        }
        return materials;
    }

    /**
     * 处理文章内容与图片与素材的关系
     *
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContext(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章图片与内容素材的关系到数据库中
     *
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {

        //图片去重 （可能引用了同一张图片
        materials = materials.stream().distinct().collect(Collectors.toList());

        if (materials != null && !materials.isEmpty()) {
            //根据素材图片的url查询素材id
            LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.in(WmMaterial::getUrl, materials);
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(lambdaQueryWrapper);

            //判断素材是否有效
            if (wmMaterials == null || wmMaterials.size() == 0) {
                //手动抛出异常  第一个功能 能够提示调用者素材失效了 第二个功能 事务回滚
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL); //素材引用失效
            }
            if (materials.size() != wmMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL); //素材引用失效
            }


            //提取素材对象中的id
            List<Integer> wmMaterialIds = wmMaterials
                    .stream()
                    .map(wmMaterial -> wmMaterial.getId())
                    .collect(Collectors.toList());

            //wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            //批量保存
            wmNewsMaterialMapper.saveRelations(wmMaterialIds, newsId, type);
        }

    }


    /**
     * 第一个功能: 如果当前封面类型为自动 则设置封面类型的数据'
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     * <p>
     * 第二个功能：保存封面图片与素材的关系
     *
     * @param dto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {

        List<String> images = dto.getImages();

        //1.如果当前封面类型为自动 则设置封面类型的数据
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            //多图
            if (materials.size() >= 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else if (materials.size() >= 1 && materials.size() < 3) {
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            //修改文章
            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            wmNewsMapper.updateById(wmNews);
        }
        //2.保存封面图片与素材的关系
        if (images != null && images.size() > 0) {
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }

    }
}
